import { analysisIntent, IntentHandler } from "../core/tool/baseScene";
import { mathType } from "../core/tool/face";
import component, { ComType } from "../core/tool/component";
import bag_component from "./bag_component";
import rpg_component from "./rpg_component";

import equip_component from "./equip_component";
import base_component from "./base_component";
import follow_component from "./follow_component";
import talent_component from "./talent_component";
import mail_component from "./mail_component";
import sign_component from "./sign_component";
import task_component from "./task_component";
import { UserLevel } from "../shared/face";
import admin_component from "./admin_component";
import { IntentConfig, IntentHelper } from "../core/tool/intentHelper";
import { IntentService } from "../service/IntentService";
import { ModernIntentService } from "../service/ModernIntentService";
import * as fs from 'fs';
import * as path from 'path';
import sdk from "../core";

/**
 * 意图组件 - 主要负责UI交互和意图路由管理
 * 职责：
 * 1. 管理意图处理器
 * 2. 处理用户意图路由
 * 3. 注册和管理各种意图
 */
export default class intent_component extends component {
    private _intentHandlers: Map<string, IntentHandler> = new Map();
    
    // 使用依赖注入获取现代化服务
    private _modernIntentService = this.getService<ModernIntentService>('ModernIntentService');
    
    constructor() {
        super();
    }
    
    /**
     * 注册通用意图
     */
    init(): void {
        const components = this.getComponents();
        const intentConfigs = this._modernIntentService.getBasicIntentConfigs(components);
        
        // 使用服务批量注册意图
        const success = this._modernIntentService.batchRegisterIntents(intentConfigs, this.registerIntent.bind(this), this);
        if (!success) {
            console.warn('部分意图注册失败');
        }
        
        // 开发者权限检查
        this.registerAdminIntent(components);
        
    }


    
    /**
     * 获取所有组件
     * @returns 组件映射
     */
    private getComponents() {
        return {
            base: this.getComponent(ComType.base) as base_component,
            rpg: this.getComponent(ComType.rpg) as rpg_component,

            bag: this.getComponent(ComType.背包) as bag_component,
            equip: this.getComponent(ComType.装备栏) as equip_component,
            follow: this.getComponent(ComType.随从) as follow_component,
            talent: this.getComponent(ComType.血统) as talent_component,
            mail: this.getComponent(ComType.邮件) as mail_component,
            sign: this.getComponent(ComType.签到) as sign_component,
            task: this.getComponent(ComType.任务) as task_component,
            intent: this,
        };
    }
    
    /**
     * 注册管理员意图
     * @param components 组件映射
     */
    private registerAdminIntent(components: any): void {
        if (this._modernIntentService.hasAdminPermission(components.base.sys_leve)) {
            const adminComponent = this.getComponent(ComType.管理员) as admin_component;
            const adminConfig = this._modernIntentService.createAdminIntentConfig(adminComponent);
            
            this.registerIntent(
                adminConfig.mathType,
                adminConfig.command,
                adminComponent.client_main,
                adminComponent,
                true
            );
        }
    }

    /**
     * 注册意图处理器
     * @param mathType 匹配类型
     * @param mathStr 匹配字符串
     * @param action 动作函数
     * @param self 执行上下文
     * @param isHideMath 是否隐藏匹配
     */
    registerIntent(mathType: mathType, mathStr: string, action: Function, self: any = this, isHideMath: boolean = false) {
        const success = this._modernIntentService.registerIntentHandler(
            mathType,
            mathStr,
            action,
            self,
            isHideMath,
            this._intentHandlers
        );
        
        if (!success) {
            console.warn(`意图注册失败: ${mathType}-${mathStr}`);
        } else {
            // 每次注册新指令后打印更新后的列表
        }
    }
    
    /**
     * 获取排序后的意图处理器
     * @returns 排序后的意图处理器数组
     */
    getIntentHandlers() {
        const handlers = [...this._intentHandlers.values()];
        return this._modernIntentService.sortIntentHandlers(handlers);
    }
    
    /**
     * 删除意图处理器
     * @param mathType 匹配类型
     * @param mathStr 匹配字符串
     */
    delIntent(mathType: mathType, mathStr: string) {
        const success = this._modernIntentService.deleteIntentHandler(mathType, mathStr, this._intentHandlers);
        if (!success) {
            console.warn(`意图删除失败: ${mathType}-${mathStr}`);
        }
    }
    
    /**
     * 获取意图处理器统计信息
     * @returns 统计信息
     */
    getIntentHandlerStats() {
        return this._modernIntentService.getIntentHandlerStats(this._intentHandlers);
    }
    
    /**
     * 清除所有意图处理器
     */
    clearAllIntents() {
        this._modernIntentService.clearAllIntentHandlers(this._intentHandlers);
    }
    
    /**
     * 验证意图配置
     * @param config 意图配置
     * @returns 验证结果
     */
    validateIntentConfig(config: IntentConfig) {
        return this._modernIntentService.validateIntentConfig(config);
    }
    
    /**
     * 获取意图处理器总数
     * @returns 总数
     */
    getIntentHandlerCount(): number {
        return this._intentHandlers.size;
    }
    
    // 注释掉的代码保留以防需要
    // delComAllIntent(name: string) {
    //     //循环意图中 self.clsName 等于 name 的意图
    //     this.intentHandlers.forEach((item, key) => {
    //         if (item.self.clsName == name) {
    //             this.delIntent(item.mathType, item.mathStr);
    //         }
    //     });
    // }

    /**
     * 更新日志：读取项目根目录下的 codelogs 文件并逐行发送
     */
    updateLog(data: analysisIntent) {
        const formatTime = (d: Date) => {
            const pad = (n: number) => n.toString().padStart(2, '0');
            const yyyy = d.getFullYear();
            const mm = pad(d.getMonth() + 1);
            const dd = pad(d.getDate());
            const hh = pad(d.getHours());
            const mi = pad(d.getMinutes());
            const ss = pad(d.getSeconds());
            return `${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss}`;
        };

        let card = sdk.tool.card.create();
        card.title('更新日志');
        try {
            const logPath = path.join(process.cwd(), 'codelogs');
            if (!fs.existsSync(logPath)) {
                card.l(`最后更新时间: 未知`);
                card.l('暂无更新内容');
                this.client_text(card.getText());
                return;
            }

            const stat = fs.statSync(logPath);
            card.l(`最后更新: ${formatTime(stat.mtime)}`);
            card.title('更新内容')

            const content = fs.readFileSync(logPath, 'utf-8');
            const lines = content
                .split(/\r?\n/)
                .map(line => line.trim())
                .filter(line => line.length > 0);

            if (lines.length === 0) {
                card.l('暂无更新内容');
                this.client_text(card.getText());
                return;
            }

            for (const line of lines) {
                card.l(line);
            }
            card.title('开源地址');
            card.l('npm:koishi-plugin-dew-bot');
            this.client_text(card.getText());
        } catch (err) {
            console.error('读取更新日志失败:', err);
            this.client_text('读取更新日志失败');
        }
    }
}

